<template>
  <div class="container">
    <!-- 暂时隐藏，请勿删除 -->
    <div class="reminder">
      <i class="el-icon-warning"></i>
      PC端需要使用身份证阅读器录入人员，如您没有身份证阅读器，可下载
      <el-link type="primary" id="downloadApp" @click="downloadApp"
        >工匠365 企业版APP</el-link
      >录入人员
      <div class="generateQRcode" id="generateQRcode" style="display: none">
        <img :src="qrCode_Url" alt="" />
        <p>Android版</p>
        <p>扫描二维码下载</p>
      </div>
    </div>
    <topTitle
      :titleText="titleText"
      :back="back"
      @gobackTriser="goback"
    ></topTitle>
    <div class="mainCon">
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formData"
        label-width="164px"
        class="demo-ruleForm"
      >
        <!-- 身份信息 -->
        <el-row>
          <el-col class="identityInfoTitle titleInfo">
            <div>身份信息</div>
          </el-col>
        </el-row>

        <el-row class="identityInfo">
          <el-col :span="18">
            <div class="grid-content bg-purple">
              <el-row>
                <el-col :span="11">
                  <el-form-item prop="employeeName" label="人员姓名：">
                    <el-input
                      v-model="formData.employeeName"
                      id="employeeName"
                      disabled
                      placeholder="根据阅读器读入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item prop="idCard" label="身份证号：">
                    <el-input
                      v-model="formData.idCard"
                      id="idCard"
                      disabled
                      placeholder="根据阅读器读入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="11">
                  <el-form-item prop="employeeSex" label="人员性别：">
                    <el-select
                      class="selectWidth"
                      v-model="formData.employeeSex"
                      id="employeeSex"
                      disabled
                      placeholder="根据阅读器读入"
                    >
                      <el-option
                        v-for="item in sexOption"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item prop="employeeBirth" label="出生日期：">
                    <el-input
                      v-model="formData.employeeBirth"
                      id="employeeBirth"
                      disabled
                      placeholder="根据阅读器读入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="11">
                  <el-form-item prop="employeeNation" label="人员民族：">
                    <el-select
                      class="selectWidth"
                      v-model="formData.employeeNation"
                      id="employeeNation"
                      disabled
                      placeholder="根据阅读器读入"
                    >
                      <el-option
                        v-for="item in nationOptions"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="文化程度：" prop="edu">
                    <el-select
                      class="selectWidth"
                      v-model="formData.edu"
                      placeholder="请选择"
                      clearable
                    >
                      <el-option
                        v-for="item in eduOptions"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="11">
                  <el-form-item label="婚姻状况：" prop="maritalStatus">
                    <el-select
                      class="selectWidth"
                      v-model="formData.maritalStatus"
                      placeholder="请选择"
                      clearable
                    >
                      <el-option
                        v-for="item in marrigeOptions"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="政治面貌：" prop="politicalStatus">
                    <el-select
                      class="selectWidth"
                      v-model="formData.politicalStatus"
                      placeholder="请选择"
                      clearable
                    >
                      <el-option
                        v-for="item in politicalOptions"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="22">
                  <el-form-item label="家庭住址：" prop="homeAddress">
                    <el-input
                      v-model="formData.homeAddress"
                      id="homeAddress"
                      disabled
                      placeholder="根据阅读器读入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
          <el-col :span="6" style="padding-left: 50px">
            <input name="image64" type="hidden" id="image64" />
            <div id="readIdCardBox" class="readIdCardBox">
              <ul>
                <li>
                  <img
                    src="../../../static/img/employee/card.png"
                    id="cardImg"
                    style="width: 100px"
                  />
                </li>
                <li
                  style="margin-top: 10px"
                  id="readIdCard"
                  @click="readCard('add')"
                >
                  <div class="btnBox fontBorderTheme">
                    <div class="imgBox bgcTheme">
                      <img
                        class="iconImg"
                        style="width: 10px; height: 10px"
                        src="../../../static/img/employee/head.png"
                        alt=""
                      />
                    </div>
                    <div class="textBox fontColorTheme">读取身份信息</div>
                  </div>
                  <!-- <img src="../../../static/img/employee/readidcard.png" style="cursor:pointer"/> -->
                </li>
                <li>
                  <a
                    href="javascript:;"
                    class="driveDownload"
                    id="idCardDriver"
                    @click="downLoad('idCardDriver')"
                    >安装身份证读取器及人脸采集设备驱动</a
                  >
                </li>
                <li>
                  <a
                    href="javascript:;"
                    class="driveDownload"
                    id="operateAddEmploy"
                    @click="downLoad('operateAddEmploy')"
                    >查看操作文档</a
                  >
                </li>
              </ul>
            </div>
          </el-col>
        </el-row>

        <!-- 基础信息 -->
        <!-- <el-row>

                </el-row> -->
        <el-row class="identityInfo">
          <el-col :span="18">
            <el-col :span="24">
              <el-col class="basicInfoTitle titleInfo">
                <div>基础信息</div>
              </el-col>
            </el-col>
            <el-col :span="24">
              <div class="grid-content bg-purple">
                <el-row>
                  <el-col :span="11">
                    <el-form-item label="工资卡银行：" prop="bankId">
                      <el-select
                        class="selectWidth"
                        v-model="formData.bankId"
                        placeholder="请选择"
                        clearable
                      >
                        <el-option
                          v-for="item in bankOptions"
                          :key="item.code"
                          :label="item.name"
                          :value="item.code"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item label="银行卡号：" prop="accountId">
                      <el-input
                        v-model="formData.accountId"
                        @blur="formData.accountId = changeValue($event)"
                        placeholder="请输入银行卡号"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="11">
                    <el-form-item label="手机号码：" prop="tel">
                      <el-input
                        v-model="formData.tel"
                        @blur="formData.tel = changeValue($event)"
                        placeholder="请输入手机号码"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item label="务工卡号：" prop="attNo">
                      <el-input
                        v-model="formData.attNo"
                        @blur="formData.attNo = changeValue($event)"
                        placeholder="请输入务工卡号"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-col>
          </el-col>
          <el-col :span="6" style="padding-left: 50px">
            <!-- <input name='image64' type='hidden' id="image64" /> -->
            <div class="readIdCardBox faceCollectBox">
              <ul>
                <li>
                  <img :src="collectImg" style="width: 100px" />
                </li>
                <li style="margin-top: 10px" @click="faceCollection()">
                  <!-- <img src="../../../static/img/face/collect.png" style="cursor:pointer;width: 86px;height: 21px;"/> -->
                  <div class="btnBox fontBorderTheme">
                    <div class="imgBox bgcTheme">
                      <img
                        class="iconImg"
                        style="width: 10px; height: 10px"
                        src="../../../static/img/employee/head.png"
                        alt=""
                      />
                    </div>
                    <div class="textBox fontColorTheme">读取身份信息</div>
                  </div>
                </li>
                <a id="openExe" href="CardRead://"></a>
              </ul>
            </div>
          </el-col>
        </el-row>
        <!-- 合同信息 -->
        <el-row>
          <el-col class="contractInfoTitle titleInfo">
            <div>合同信息</div>
          </el-col>
        </el-row>

        <el-row class="identityInfo">
          <el-col :span="18">
            <div class="grid-content bg-purple">
              <el-row>
                <el-col :span="11">
                  <el-form-item
                    class="selectWidth"
                    label="所在部门："
                    prop="orgId"
                  >
                    <el-cascader
                      class="selectWidth"
                      v-model="orgId"
                      :options="orglist"
                      :props="{ checkStrictly: true }"
                      @change="handleChange"
                      clearable
                    ></el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="职位：" prop="employeeType">
                    <el-input
                      v-model="formData.employeeType"
                      @blur="formData.employeeType = changeValue($event)"
                      placeholder="请输入职位"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="11">
                  <el-form-item prop="date" label="雇佣周期：">
                    <el-date-picker
                      v-model="formData.date"
                      type="daterange"
                      unlink-panels
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="yyyy-MM-dd"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="基本工资：" prop="standardSalary">
                    <el-input
                      v-model="formData.standardSalary"
                      @blur="formData.standardSalary = changeValue($event)"
                      placeholder="请输入基本工资"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="1" class="wageUnit"> 元/月 </el-col>
              </el-row>
              <el-row>
                <el-col :span="22">
                  <el-form-item label="合同附件：">
                    <uploadAnnex
                      @getFileList="getFileList"
                      :limitationFactor="limitationFactor"
                      @getFile="getFile"
                      :upLoadFile="upLoadFile"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="22" v-model="formData.contractImgUrl">
                  <!-- <elementImage :upLoadFile="upLoadFile"   :srcList="srcList" :oldSrcList="oldSrcList" @changeSrcList="changeSrcList"></elementImage> -->
                  <uploadResult
                    :resultList="upLoadFile"
                    @callBackResult="getFile"
                  />
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
        <el-row style="text-align: center; margin-top: 20px">
          <el-col :span="16">
            <el-form-item>
              <el-button
                class="commonBut saveBtn"
                type="primary"
                @click="saveToDetail"
                :loading="isSaveLoading"
                >保存</el-button
              >
              <el-button
                class="commonBut saveBtn"
                type="primary"
                id="saveAdd"
                @click="saveReset"
                :loading="isSaveAgainLoading"
                >保存并继续添加</el-button
              >
              <el-button class="commonBut" @click="goback">返回</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <rewardsReminder
      v-if="hasRecord"
      :employeeCreditList="employeeCreditList"
    ></rewardsReminder>
  </div>
</template>

<script>
import common from '../../kits/common'
//信用提示
import rewardsReminder from '@/components/worker/rewardsReminder'

export default {
  name: 'employeeAdd',
  timerID: 0,
  socket: null,
  keepAlive: null,
  components: {
    rewardsReminder,
  },
  data() {
    var checkArea = (rule, value, callback) => {
      var that = this
      if (!that.orgId || that.orgId.length < 1) {
        return callback(new Error('所在部门不能为空'))
      } else {
        callback()
      }
    }
    return {
      limitationFactor: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传文件最大数量设置
        fileSize: 5, //自定义上传文件最大设置
        messageFileSizetip: '最多能上传2M以内的图片', //自定义id解决一个页面包含多个上传附件
        messagetip: '要求格式为JPG、PNG格式，图片大小不超过5M', //自定义报错提示语
        formatType: 'typeOne', //自定义上传格式校验类型
        fileId: 'salaryExcel', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'salaryExcelForm', //自定义id解决一个页面包含多个上传附件
        methodTip: '合同附件支持png，jpg，jpeg', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
      },
      titleText: '添加人员',
      back: true,
      formData: {
        employeeName: '', //人员姓名
        idCard: '', //身份证号
        employeeSex: '', //性别
        employeeBirth: '', //出生日期
        tel: '', //手机号码
        employeeNation: '', //名族
        homeAddress: '', //家庭住址
        edu: '', //教育程度
        politicalStatus: '', //政治面貌
        maritalStatus: '', //婚姻状况
        bankId: '', //工资银行
        accountId: '', //工资卡号
        orgId: '', //部门
        date: [],
        data: [], //日期区间
        // startDate: "", //雇佣开始时间
        // endDate: "" , //雇佣结束时间
        employeeType: '', //职位
        standardSalary: '', //基本工资
        employeeImgUrl: [], //员工身份证头像
        contractImgUrl: [], //合同附件
        attNo: '', //务工卡号
        faceCameraPhoto: [], //人脸采集头像
      },
      orgId: '', //部门
      sexOption: [],
      nationOptions: [],
      bankOptions: [],
      eduOptions: [],
      marrigeOptions: [],
      politicalOptions: [],
      orglist: [], //部门
      formRules: {
        employeeName: [
          {
            required: true,
            message: '请根据阅读器读入',
            trigger: 'blur',
          },
        ],
        idCard: [
          {
            required: true,
            message: '请根据阅读器读入',
            trigger: 'blur',
          },
        ],
        employeeSex: [
          {
            required: true,
            message: '请根据阅读器读入',
            trigger: 'blur',
          },
        ],
        employeeBirth: [
          {
            required: true,
            message: '请根据阅读器读入',
            trigger: 'blur',
          },
        ],
        employeeNation: [
          {
            required: true,
            message: '请根据阅读器读入',
            trigger: 'blur',
          },
        ],
        orgId: [
          {
            required: true,
            validator: checkArea,
            // message: "所在部门不能为空",
            trigger: ['blur', 'change'],
          },
        ],
        date: [
          {
            required: true,
            message: '请选择日期',
            trigger: 'blur',
          },
        ],
        tel: [
          {
            // required: true,
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
          },
        ],
        accountId: [
          {
            // required: true,
            pattern: /^\d{15,19}$/,
            message: '请输入15-19 位纯数字的银行卡号',
            trigger: 'blur',
          },
        ],
        standardSalary: [
          {
            // required: true,
            pattern: /^\d{1,7}(\.\d{0,2})?$/,
            message: '已超过金额最大值，请重新输入',
            trigger: 'blur',
          },
        ],
        attNo: [
          {
            // required: true,
            pattern: /^[^\u4e00-\u9fa5]{0,}$/,
            message: '请输入非汉字的务工卡号',
            trigger: 'blur',
          },
        ],
      },
      employeeId: '', //务工id
      contractId: '', //合同id
      upLoadFile: [], //附件
      cardFile: [],
      srcList: [],
      oldSrcList: [],
      isSaveLoading: false, // 保存loading
      isSaveAgainLoading: false,
      qrCode_Url: '', //二维码
      czSrc: require('../../../static/img/employee/card.png'),
      collectImg: require('../../../static/img/employee/card.png'),
      hasRecord: false, //是否有不良记录，奖励信息
      employeeCreditList: [], //不良记录，奖励信息记录
    }
  },
  created() {
    //字典表下拉框
    this.getSelectData('SEX')
    this.getSelectData('NATION')
    this.getSelectData('EDU')
    this.getSelectData('MARRIAGE')
    this.getSelectData('POLITICAL')
    this.getSelectData('BANK_TYPE')
    // 部门下拉框
    this.getOrglist()
  },
  mounted() {
    this.clickDocument()
  },
  methods: {
    /**
     * @description: 获取上传的附件
     */
    getFileList(val) {
      this.oldSrcList.push(val)
      this.srcList.push(val)
    },
    /**
     * @description: 获取上传的附件
     */
    getFile(val) {
      this.upLoadFile = val
    },
    downloadApp() {
      if (!this.isEsUser()) {
        this.$message({
          showClose: true,
          message: 'app上架审核中',
          type: 'warning',
          duration: 1500,
        })
      } else {
        event.stopPropagation()
        $('#generateQRcode').toggle()
        //获取二维码
        this.getQRcode()
      }
    },
    clickDocument() {
      $(document).click(function () {
        $('#generateQRcode').hide()
      })
    },
    downLoad(type) {
      this.axios({
        method: 'post',
        url: 'api-su/salary/expand/findurl',
        data: {
          name: type,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              window.open(response.data.result.url)
            } else {
              this.$message({
                type: 'error',
                message: response.data.msg,
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    getQRcode() {
      this.axios({
        method: 'post',
        url: 'api-bs/upgrade/check',
        data: {
          enName: 'gj365_nc',
        },
      })
        .then(
          (response) => {
            this.qrCode_Url = response.data.qrCode_Url
          },
          (response) => {}
        )
        .catch((error) => {})
    },

    /**
     * @description: 改变图片地址
     */
    changeSrcList(val) {
      this.srcList = val
    },
    getSelectData(dicitemType) {
      this.axios({
        method: 'post',
        url: 'api-bs/base/dicitem/findbytype',
        data: {
          type: dicitemType,
        },
      })
        .then((response) => {
          if (dicitemType == 'SEX') {
            this.sexOption = response.data.result
          } else if (dicitemType == 'NATION') {
            this.nationOptions = response.data.result
          } else if (dicitemType == 'EDU') {
            this.eduOptions = response.data.result
          } else if (dicitemType == 'MARRIAGE') {
            this.marrigeOptions = response.data.result
          } else if (dicitemType == 'POLITICAL') {
            this.politicalOptions = response.data.result
          } else if (dicitemType == 'BANK_TYPE') {
            this.bankOptions = response.data.result
          }
        })
        .catch((response) => {})
    },
    getOrglist() {
      this.axios({
        method: 'post',
        url: 'api-c/organization/base/org/arc',
        data: {},
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.orglist = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    handleChange(item) {
      var orgId = this.orgId[this.orgId.length - 1]
      this.formData.orgId = orgId
    },
    //读取身份证信息
    getbrowser() {
      if (!!window.ActiveXObject || 'ActiveXObject' in window) return true
      else return false
    },
    //身份证阅读器阅读
    readCard(handle) {
      this.buildWS(handle)
    },
    buildWS(handle) {
      var that = this
      //判断浏览器兼容性
      if (!this.checkBrowser()) {
        return false
      }
      //点击间隔控制
      this.perRead()
      // 本机IP（因为我们的C++程序安装在用户自己的电脑上，所以固定为127.0.0.1）
      var localIp = '127.0.0.1'
      // WebSocket服务的端口（该端口在C++正式上线时，需要指定一个唯一的端口）
      // 另外，这个端口最好是不常用的；再者，C++程序中针对端口这一块，最好多设置几个，当有端口被占用时，循环其他的端口，当然前端JS做同样的处理
      var localPort = '10080'
      // 应用名（或者工程名）
      var appName = 'ws'
      // 服务端WebSocket的访问路径（可自由指定）
      var serverPath = 'webSocket'
      // WebSocket的通道名称
      // 因为WebSocket服务端可以与多个客户端建立连接，为了区分不同的客户端，在客户端发起连接请求时，需要为连接的通道指定唯一标识
      // 因为我们开发的是C++服务端，安装在用户自己电脑上，所以实际应用时，一个服务端也只是对应一个客户端，所以这个channel有没有都没有关系
      var channel = 'zhangsan'
      // WebSocket服务端访问路径
      //var url = "ws://" + localIp + ":" + localPort + "/" + appName + "/" + serverPath + "/" + channel;
      var url = 'ws://' + localIp + ':' + localPort
      // 以上只是为了说明websocket的访问地址的相关组成部分
      // 实际应用中，可以把WebSocket的服务端地址固定下来，就没有必要再定义这么多变量了
      // 例如：var url = "ws://127.0.0.1:8080/ws/webSocket/zhangsan";
      this.closeSocket()
      if (this.socket == null) {
        this.socket = new WebSocket(url)
        //resultMsg("WebSocket连接【new socket】，socket连接状态："+socket.readyState);
      } else {
        //resultMsg("WebSocket连接已经建立.socket连接状态："+socket.readyState);
      }
      try {
        // WebSocket已经成功建立连接
        this.socket.onopen = function (msg) {
          that.keepAlive() //保持连接
          //resultMsg("WebSocket连接【onopen】socket连接状态："+socket.readyState);
          that.readIDCard()
        }
        // WebSocket建立连接失败
        this.socket.onerror = function () {
          //resultMsg("WebSocket连接【onerror】socket连接状态："+socket.readyState);
          //swal("请先下载并运行\r\n【身份证阅读程序.exe】");
          //that.$message({ message: "请先下载并运行\r\n【身份证阅读程序.exe】"});
          that.$message({
            showClose: true,
            message:
              '请先下载并运行\r\n【身份证阅读程序.exe】\r\n如已下载该程序，请检查程序是否已正常安装并启动',
            type: 'error',
            duration: 3000,
          })
        }
        // 监听WebSocket的消息通道
        // 当消息通道中有消息时，会自动触发该函数
        this.socket.onmessage = function (msg) {
          // 当C++调用精伦的身份证接口成功获取到身份证信息时，将身份证信息放入消息通道
          // 前端可以直接从消息通道中获取到C++发送的消息
          //resultMsg("前端已经监听到WebSocket服务端有消息发来,【onmessage】socket连接状态："+socket.readyState);
          //resultMsg("从WebSocket的消息通道中获取到的身份证信息：\n");
          //resultMsg("websocket 消息通道："+msg.data);

          if (msg && msg.data == 'false') {
            //swal("请将身份证移开\r\n重新将卡片放到读卡器上!");
            //this.$message({ message: "请将身份证移开\r\n重新将卡片放到读卡器上!"});
            that.$message({
              showClose: true,
              message: '请将身份证移开\r\n重新将卡片放到读卡器上!',
              type: 'error',
              duration: 3000,
            })
          } else if (msg && msg.data == 'error') {
            //swal("请检查【身份证阅读器】\r\n连接是否正常!");
            //this.$message({ message: "请检查【身份证阅读器】\r\n连接是否正常!"});
            that.$message({
              showClose: true,
              message: '请检查【身份证阅读器】\r\n连接是否正常!',
              type: 'error',
              duration: 3000,
            })
          } else {
            var returnObj = JSON.parse(msg.data)
            //resultMsg(returnObj);
            //var typeId1 = $("#typeId1").val();
            if (handle == 'add') {
              that.setIdcardData(returnObj)
            }
          }
          // 获取到信息后，关闭WebSocket
          that.closeSocket()
        }
      } catch (ex) {
        //swal("连接异常,请检查是否打开\r\n【身份证阅读程序.exe】");
        //this.$message({ message: "连接异常,请检查是否打开\r\n【身份证阅读程序.exe】"});
        that.$message({
          showClose: true,
          message: '连接异常,请检查是否打开\r\n【身份证阅读程序.exe】',
          type: 'error',
          duration: 3000,
        })
      }
    },
    checkBrowser() {
      if (window.WebSocket) {
        return true
      } else {
        this.$message({
          message:
            '我们强烈建议您使用谷歌、火狐、360极速、Opera 等浏览器，如要使用IE，请使用IE10及以上版本',
        })
        return false
      }
    },
    perRead() {
      var second = 3 //3秒
      var time = setInterval(function () {
        if (second > 0) {
          $('#readIdCard').attr('disabled', true)
          second--
        } else {
          $('#readIdCard').removeAttr('disabled')
          clearInterval(time)
        }
      }, 1000)
    },
    closeSocket() {
      try {
        if (this.socket != null) {
          this.socket.close()
          this.socket = null
        }
        this.cancelKeepAlive()
      } catch (ex) {}
    },
    keepAlive() {
      var timeout = 1000

      if (this.socket && this.socket.readyState == this.socket.OPEN) {
        this.socket.send('')
      }
      this.timerID = setTimeout(this.keepAlive, timeout)
    },
    cancelKeepAlive() {
      if (this.timerID) {
        this.clearTimeout(timerID)
      }
    },
    readIDCard() {
      try {
        // 前端JS向C++的WebScoket服务发送读取身份证信息的指令
        // C++的WebScoket服务获取到指令后，对指令进行判断，如果是READ_ID_CARD，那么C++调用精伦的读取身份证信息接口
        // C++获取到身份证信息后，把信息放入消息通道即可
        this.socket.send('ID_CARD_RED')
      } catch (ex) {
        //swal("信息设置异常,请检查是否成功运行【身份证阅读程序.exe】.")
        this.$message({
          message: '信息设置异常,请检查是否成功运行【身份证阅读程序.exe】',
        })
        //resultMsg("【readIDCard】连接异常,请检查是否成功运行【身份证阅读程序.exe】.");
        //resultMsg("【readIDCard】请重新建立WebScoket连接.");
      }
    },
    setIdcardData(obj) {
      this.formData.employeeName = obj.Name
      this.formData.idCard = obj.IDCard
      this.getEmployeeCreditList(obj.Name, obj.IDCard)
      this.formData.homeAddress = obj.Address
      var val =
        obj.Birthday.substring(0, 4) +
        '-' +
        obj.Birthday.substring(4, 6) +
        '-' +
        obj.Birthday.substring(6, 8)
      this.formData.employeeBirth = val

      if (obj.Sex == '女') {
        this.formData.employeeSex = '2' //女
      } else {
        this.formData.employeeSex = '1' //男
      }

      var nation = this.nationOptions.find((item) => {
        return item.name === obj.Nation + '族'
      })
      this.formData.employeeNation = nation.code
      $('#image64').val(obj.ImgCode) //身份证图片
      this.showImg()
      //存在身份证信息就掉已存在的信息接口
      this.getExistInfo(this.formData.idCard)
    },
    getExistInfo(idCard) {
      this.axios({
        method: 'post',
        url: 'api-e/nc/employee/expand/employees/idcard',
        data: {
          idcard: idCard,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              var data = response.data.result
              this.formData.edu = data.edu
              this.formData.maritalStatus = data.maritalStatus
              this.formData.politicalStatus = data.politicalStatus
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    //身份证图片
    showImg(name) {
      var that = this
      var img = $('#image64').val()
      //保存并继续添加需要先清空身份证数组
      that.cardFile = []
      this.axios({
        method: 'post',
        url: 'api-f/files/upload/base64',
        data: {
          image64: img,
        },
      })
        .then((response) => {
          var data = response.data
          var cardUrl = data.url
          var key = 'remark'
          var value = 'IDCARD_READER' //身份证上传标识
          data[key] = value
          that.cardFile.push(response.data)
          $('#cardImg').attr('src', cardUrl)
        })
        .catch((error) => {})
    },
    //返回列表
    goback() {
      this.$router.push('/home/employee/employeeOn')
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/employee/employeeOn',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    //保存跳转到详情
    saveToDetail() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          // 保存更新
          this.isSaveLoading = true
          this.submitFormUptate('add')
        } else {
          return false
        }
      })
    },
    //保存并继续添加（当前页面不跳转）
    saveReset() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          // 保存更新
          this.isSaveAgainLoading = true
          this.submitFormUptate('addAgain')
        } else {
          return false
        }
      })
    },
    submitFormUptate(params) {
      var data = {
        name: this.formData.employeeName,
        idcard: this.formData.idCard,
        address: this.formData.homeAddress,
        birthday: this.formData.employeeBirth,
        tel: this.formData.tel,
        edu: this.formData.edu,
        nationality: this.formData.employeeNation,
        sex: this.formData.employeeSex,
        politicalStatus: this.formData.politicalStatus,
        maritalStatus: this.formData.maritalStatus,
        bankId: this.formData.bankId,
        accountId: this.formData.accountId,
        orgId: this.formData.orgId,
        startDate: this.formData.date[0],
        endDate: this.formData.date[1],
        employeeType: this.formData.employeeType,
        standardSalary: this.formData.standardSalary,
        employeeImgUrl: JSON.stringify(this.cardFile),
        contractImgUrl: JSON.stringify(this.upLoadFile),
        attNo: this.formData.attNo,
        faceCameraPhoto: this.formData.faceCameraPhoto,
      }
      this.axios({
        method: 'post',
        url: 'api-e/nc/employee/expand/employees/add',
        data: data,
      })
        .then((response) => {
          this.isSaveLoading = false
          this.isSaveAgainLoading = false
          if (!response.data.hasError) {
            this.$message({
              message: '保存成功',
              type: 'success',
            })
            //保存成功调取预警接口
            this.getIsAlert()
            this.employeeId = response.data.result.employId
            this.contractId = response.data.result.contractId

            if (params == 'addAgain') {
              this.$refs['formData'].resetFields()
              $('#cardImg').attr('src', this.czSrc)
              this.upLoadFile = []
              // 连续录人部门不清空
              var orgId = this.orgId[this.orgId.length - 1]
              this.formData.orgId = orgId
              this.collectImg = require('../../../static/img/employee/card.png')
              this.formData.faceCameraPhoto = []
            } else if (params == 'add') {
              this.$router.push({
                path: '/home/employee/employeeDetail',
                name: 'employeeDetail',
                query: {
                  employeeId: this.employeeId,
                  contractId: this.contractId,
                },
              })
              this.$store.commit('CHANGE_SLIDER_NAME', {
                oldUrl: '/home/employee/employeeOn',
                newUrl: this.$router.currentRoute.fullPath,
              })
            }
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
            this.isSaveLoading = false
            this.isSaveAgainLoading = false
          }
        })
        .catch((error) => {
          this.$message.error('保存失败')
          this.isSaveLoading = false
          this.isSaveAgainLoading = false
        })
    },
    getIsAlert() {
      var data = {
        name: this.formData.employeeName,
        idCard: this.formData.idCard,
      }
      this.axios({
        method: 'post',
        url: 'api-a/nc/alert/base/addchildalert',
        data: data,
      })
        .then((response) => {})
        .catch((error) => {})
    },
    //点击人脸采集
    faceCollection() {
      var that = this
      //判断浏览器兼容性
      if (!this.checkBrowser()) {
        return false
      }
      //点击间隔控制
      // this.perRead();

      var localIp = '127.0.0.1'
      // WebSocket服务的端口（该端口在C++正式上线时，需要指定一个唯一的端口）
      // 另外，这个端口最好是不常用的；再者，C++程序中针对端口这一块，最好多设置几个，当有端口被占用时，循环其他的端口，当然前端JS做同样的处理
      var localPort = '10080'
      // 应用名（或者工程名）
      var appName = 'ws'
      // 服务端WebSocket的访问路径（可自由指定）
      var serverPath = 'webSocket'
      // WebSocket的通道名称
      // 因为WebSocket服务端可以与多个客户端建立连接，为了区分不同的客户端，在客户端发起连接请求时，需要为连接的通道指定唯一标识
      // 因为我们开发的是C++服务端，安装在用户自己电脑上，所以实际应用时，一个服务端也只是对应一个客户端，所以这个channel有没有都没有关系
      var channel = 'zhangsan'
      // WebSocket服务端访问路径
      //var url = "ws://" + localIp + ":" + localPort + "/" + appName + "/" + serverPath + "/" + channel;
      var url = 'ws://' + localIp + ':' + localPort
      // 以上只是为了说明websocket的访问地址的相关组成部分
      // 实际应用中，可以把WebSocket的服务端地址固定下来，就没有必要再定义这么多变量了
      // 例如：var url = "ws://127.0.0.1:8080/ws/webSocket/zhangsan";
      if (this.socket != null) {
        this.socket.close()
        this.socket = null
      }

      if (this.socket == null) {
        this.socket = new WebSocket(url)
      } else {
        console.log(
          'WebSocket连接已经建立.socket连接状态：' + socket.readyState
        )
      }
      try {
        // WebSocket已经成功建立连接
        this.socket.onopen = function (msg) {
          try {
            // 前端JS向C++的WebScoket服务发送人脸识别的指令
            // C++的WebScoket服务获取到指令后，对指令进行判断
            // C++获取到人脸信息后，把信息放入消息通道即可
            var message = {
              type: 2,
              command: 'ID_FACE_RED',
            }
            that.toOpenFaceCollect()
            //socket.send(JSON.stringify(message));
          } catch (ex) {
            // swal("信息设置异常,请检查是否成功运行【身份证阅读程序.exe】.")
            //resultMsg("【readIDCard】连接异常,请检查是否成功运行【身份证阅读程序.exe】.");
            //resultMsg("【readIDCard】请重新建立WebScoket连接.");
          }
        }
        // WebSocket建立连接失败
        this.socket.onerror = function () {
          $('#openExe').click()
        }
        // 监听WebSocket的消息通道
        // 当消息通道中有消息时，会自动触发该函数
        this.socket.onmessage = function (msg) {
          // 前端可以直接从消息通道中获取到C++发送的消息
          //resultMsg("前端已经监听到WebSocket服务端有消息发来,【onmessage】socket连接状态："+socket.readyState);
          //resultMsg("从WebSocket的消息通道中获取到的身份证信息：");
          //resultMsg("websocket 消息通道："+msg.data);

          if (msg) {
            var returnObj = JSON.parse(msg.data)
            var imageCode = returnObj.ImgCode
            var src = 'data:image/png;base64,' + imageCode

            that.changeFacePic(src)
            // $('#face').attr("src","data:image/png;base64,"+imageCode)
          }
          // 获取到信息后，关闭WebSocket
          // this.socket.close()
          that.closeSocket()
          this.socket = null
        }
      } catch (ex) {}
    },
    toOpenFaceCollect() {
      this.socket.send('ID_FACE_RED')
    },
    changeFacePic(src) {
      this.collectImg = src
      this.uploadBase64(src)
    },
    uploadBase64(src) {
      this.axios({
        method: 'post',
        url: 'api-f/files/upload/base64',
        data: {
          image64: src,
        },
      })
        .then((response) => {
          var arr = []
          arr.push(response.data)
          this.formData.faceCameraPhoto = JSON.stringify(arr)
        })
        .catch((error) => {})
    },
    // 获取不良记录，奖励信息列表
    getEmployeeCreditList(name, idcard) {
      this.axios({
        method: 'post',
        url: 'api-r/employee/creditrecord/findEmployeeCreditByIdcard',
        data: { type: '', name: name, idcard: idcard },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.employeeCreditList = response.data.result || []
            if (this.employeeCreditList.length > 0) {
              this.hasRecord = true
            }
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {
          this.$message({
            showClose: true,
            duration: 3000,
            message: '获取数据失败',
            type: 'error',
          })
        })
    },
  },
}
</script>

<style lang="less" scoped>
.container {
  // 页面提示
  .reminder {
    color: #666;
    font-size: 14px;
    background: #fffbe6;
    line-height: 36px;
    border-radius: 3px;
    padding: 0 24px;
    i {
      color: #ffaa00;
      margin-right: 4px;
      font-size: 20px;
      vertical-align: -2px;
    }
    .el-link {
      vertical-align: baseline;
      position: relative;
    }
    .generateQRcode {
      position: absolute;
      background: #fff;
      width: 180px;
      padding: 20px 40px;
      text-align: center;
      z-index: 9999;
      left: 492px;
      margin-top: 10px;
      img {
        width: 110px;
      }
    }
  }
  .mainCon {
    padding-top: 0;
    padding-right: 24px;
    height: calc(100% - 103px);
    overflow-y: auto;
  }
  form.el-form {
    background: #fff;
    .selectWidth {
      width: 100%;
    }
    .topTitle {
      background: #e4ebf1;
      height: 67px;
      padding-left: 24px;
      font: bold 18px/67px Microsoft YaHei;
    }
    .titleInfo {
      background: #e4ebf1;
      width: 108px;
      height: 36px;
      text-align: center;
      color: #fff;
      margin-top: 24px;
      margin-bottom: 20px;
      font: bold 14px/36px Microsoft YaHei;
    }
    .identityInfoTitle {
      background: #02a2aa;
    }

    .driveDownload {
      color: #409eff;
      font-size: 12px;
      margin-top: 10px;
      // border-bottom: 1px solid #409eff;
      text-align: center;
      &:hover {
        color: #409eff;
        border-bottom: 1px solid #409eff;
      }
    }
    .basicInfoTitle {
      background: #67ace4;
    }
    .contractInfoTitle {
      background: #f9a243;
    }
    .uploadBox {
      position: relative;
      .uploadImg {
        width: 96px;
        height: 36px;
        color: #009588;
        border: 1px solid #009588;
        line-height: 10px;
      }
      .uploadImgState {
        font-size: 14px;
        color: #999999;
        margin-left: 12px;
      }
      .upLoadDom {
        position: absolute;
        top: 0;
        left: 0;
        opacity: 0;
        input {
          width: 100px;
          height: 36px;
          cursor: pointer;
        }
      }
    }
    .imgStyle {
      padding-left: 100px;
      li {
        position: relative;
        margin-right: 20px;
        margin-top: 10px;
        i {
          position: absolute;
          right: -6px;
          top: -10px;
          font-size: 20px;
        }
      }
    }
    .wageUnit {
      font-size: 14px;
      color: #666;
      margin: 8px;
    }
    .saveBtn {
      background-color: #009588;
      border-color: #009588;
      color: #fff;
    }
  }
  .el-main .el-form-item {
    margin-bottom: 20px;
  }
  .el-date-editor--daterange.el-input,
  .el-date-editor--daterange.el-input__inner,
  .el-date-editor--timerange.el-input,
  .el-date-editor--timerange.el-input__inner {
    /* width: 350px; */
    width: 100%;
  }
}

.faceCollectBox {
  margin-top: 35px;
}

.readIdCardBox {
  text-align: center;
  width: 205px;
}
.btnBox {
  width: 100px;
  height: 20px;
  font-size: 0;
  border-radius: 3px;
  border: 1px solid #409eff;
  margin: 0 auto;
  cursor: pointer;
  .imgBox {
    width: 16px;
    height: 100%;
    display: inline-block;
    position: relative;
    .iconImg {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }
  .textBox {
    width: calc(100% - 16px);
    height: 100%;
    line-height: 20px;
    display: inline-block;
    vertical-align: top;
    font-size: 12px;
    text-align: center;
  }
}
</style>
